package com.application.service.orderbusi;

import com.application.common.Constant;
import com.application.model.Message;
import com.application.model.Order;
import com.application.model.VipChargeType;
import com.application.module.buyvip.BuyVip;
import com.platform.mvc.user.User;

import java.util.Calendar;
import java.util.Date;

public class VipChargeOrderNotify implements IOrderNotify {
    @Override
    public boolean handler(Order order) {
        User user = User.dao.findById(order.getOrder_userid());
        if (user != null) {
            //1
            VipChargeType type = VipChargeType.dao.findById(order.getModule_id());
            Calendar c = Calendar.getInstance();
            if(user.get("role_date") != null) {
                Date roleDate = user.getDate("role_date");
                c.setTime(roleDate);
            }
            String suffix = "年";
            if (type.getExpire_type().equalsIgnoreCase(VipChargeType.TYPE_YEAR)) {
                c.add(Calendar.YEAR, type.getExpire_num());
            } else if(type.getExpire_type().equalsIgnoreCase(VipChargeType.TYPE_MONTH)) {
                c.add(Calendar.MONTH, type.getExpire_num());
                suffix = "月";
            } else {
                c.add(Calendar.DAY_OF_MONTH, type.getExpire_num());
                suffix = "日";
            }
            boolean f2 = user.set("role_date", c.getTime())
                    .set("role_id", Constant.group_vip)
                    .set("role_type", type.getExpire_type())
                    .set("role_date_begin", order.getPay_time())
                    .update();
            User.cacheRemove(user.getId());
            //2
            String s = type.getExpire_num() + suffix;
            String title = "高级会员充值消息";
            String content = "【高级会员充值】恭喜您成为高级会员，有效期" + s + "。";

            saveRecord(order, type);
            if (f2) {
               return Message.dao.createNotice(Message.MODULE_Charge, title, content, 0, order.getOrder_userid(),
                        "orderId:" + order.getId());
            }
        }
        return false;
    }

    private void saveRecord(Order order, VipChargeType type) {
        BuyVip vip = new BuyVip();
        vip.setUserid(order.getOrder_userid());
        vip.setVip_expire_num(type.getExpire_num());
        vip.setVip_expire_type(type.getExpire_type());
        vip.setVip_price(order.getPay_amount());
        vip.setVip_type_id(type.getId());
        vip.setCreate_time(order.getPay_time());
        vip.save();
    }


}
